package com.tianxinweb.interceptors;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tianxinweb.entity.Privilege;
import com.tianxinweb.service.PrivilegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

@Component
public class PrivilegeInterceptor implements HandlerInterceptor {

	@Autowired
	private PrivilegeService privilegeService;
	
	/**
	 * 调用目标方法直前调用，如果返回TRUE则后面的继续执行，否则结束
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		String  url=request.getServletPath().toString();
		String str[] = url.split("/");
		if(str.length>2) url = "/"+str[1]+"/"+str[2];

		List<Privilege> list = (List<Privilege>) request.getServletContext().getAttribute("allPrivilege");

		if(list==null){
			// 准备数据：allPrivilegeUrls
			list = privilegeService.selectList(null);
			request.getServletContext().setAttribute("allPrivilege", list);
		}

		for(Privilege privilege : list){
			if(url.equals(privilege.getPrivUrl()
			)){
				Integer adminId = (Integer) WebUtils.getSessionAttribute(request,"adminId");
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json; charset=utf-8");
				if(adminId==null){//如果该URL需要权限则先判断是否登录
					PrintWriter writer = response.getWriter();
					writer.write("{\"code\":-2,\"msg\":\"请先登录!\"}");
					writer.close();
					return false;
				}else{
					String adminName = (String) WebUtils.getSessionAttribute(request,"adminName");
					if("admin".equals(adminName)){//如果已登录则判断是否是admin，如果是直接放行
						return true;
					}else{
						List<Privilege> privList = (List<Privilege>)WebUtils.getSessionAttribute(request,"privilege");
						boolean flag = false;
						for(Privilege priv : privList){
							if(url.equals(priv.getPrivUrl())){//该管理员拥有权限
								flag = true;
								break;
							}
						}
						if(flag){
							return true;
						}else{
							PrintWriter writer = response.getWriter();
							writer.write("{\"code\":-3,\"msg\":\"没有访问权限!\"}");
							writer.close();
							return false;
						}
					}
				}

			}
		}
		
		return true;
	}
	
	/**
	 * 调用目标方法之后，渲染视图之前调用
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView arg3)
			throws Exception {
		 
	}
	
	/**
	 * 渲染视图之后调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}
}
